package com.ebt.m.customer.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.ebt.m.AppInitService;
import com.ebt.m.R;
import com.ebt.m.commons.utils.NetUtils;
import com.ebt.m.commons.utils.RxUtil;
import com.ebt.m.customer.constant.CustomerConstant;
import com.ebt.m.customer.entity.CustomerDetail;
import com.ebt.m.customer.event.EventCustomerChooseAdded;
import com.ebt.m.customer.event.EventCustomerListRefresh;
import com.ebt.m.customer.event.EventCustomerRefresh;
import com.ebt.m.customer.model.CustomerModelNew;
import com.ebt.m.customer.net.http.OSSUploader;
import com.ebt.m.customer.net.json.CustomerCRUDRetJson;
import com.ebt.m.customer.util.CustomerConvertUtil;
import com.ebt.m.customer.util.ToastUtil;
import com.ebt.m.data.CustomerData;
import com.ebt.m.data.rxModel.api.EBTAPI;
import com.ebt.m.utils.UIHelper;
import com.ebt.m.widget.BaseActivity;
import com.jakewharton.rxbinding2.view.RxView;
import com.tendcloud.tenddata.TCAgent;

import org.greenrobot.eventbus.EventBus;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * 此界面需要被复用，两种模式：
 * 1.新建客户
 * 2.编辑客户
 *
 * @author Rick.Wang
 */
public class ActivityCustomerDetail extends BaseActivity {

    //views
    private View mBackView;
    private View mSaveView;
    private TextView mTitleView;
    private FragmentCustomerDetail mFragmentCustomerDetail;

    //values
    private Intent mGetIntent;
    private String mCustomerMode = CustomerConstant.CUSTOMER_DETAIL_MODE_ADD;
    private String mCustomerUuid;
    private boolean mIsChooseMode;
    private EBTAPI ebtapi = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        OSSUploader.init(getApplicationContext());
        initArgs();
        initViews();
        initValues();
    }

    private void initArgs() {
        mGetIntent = getIntent();
        if (mGetIntent != null) {
            mCustomerMode = mGetIntent.getStringExtra(CustomerConstant.CUSTOMER_DETAIL_MODE);
            mCustomerUuid = mGetIntent.getStringExtra(CustomerConstant.CUSTOMER_UUID);
            mIsChooseMode = mGetIntent.getBooleanExtra(CustomerConstant.CustomerDetail.CHOOSE, false);
        }
        ebtapi = AppInitService.getEbtApi();
    }

    @Override
    public void initViews() {
        setContentView(R.layout.activity_customer_detail);
        mBackView = findViewById(R.id.btn_cancel);
        mSaveView = findViewById(R.id.btn_save);
        mTitleView = (TextView) findViewById(R.id.tv_title);
        RxView.clicks(mBackView)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(aVoid -> {
                    onBackPressed();
                });
        RxView.clicks(mSaveView)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(aVoid -> {
                    if (NetUtils.isNetworkAvailable(ActivityCustomerDetail.this)) {
                        save();
                    } else {
                        Toast.makeText(ActivityCustomerDetail.this, getApplicationContext().getString(CustomerConstant.StringPromptRes.Net.NET_NOT_AVAILABLE),
                                Toast.LENGTH_SHORT).show();
                    }
                    TCAgent.onEvent(ActivityCustomerDetail.this, "edit_customer_save");
                });
    }

    public void initValues() {
        if (CustomerConstant.CUSTOMER_DETAIL_MODE_ADD.equals(mCustomerMode)) {
            mTitleView.setText(getString(R.string.customer_new_customer));
        } else if (CustomerConstant.CUSTOMER_DETAIL_MODE_EDIT.equals(mCustomerMode)) {
            mTitleView.setText(getString(R.string.customer_edit_customer));
        }
        setDefaultFragment(mCustomerMode, mCustomerUuid, R.id.activity_customer_detail_fragment);
    }

    private void setDefaultFragment(String customerMode, String uuid, int viewId) {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        mFragmentCustomerDetail = FragmentCustomerDetail.newInstance(customerMode, uuid);
        transaction.replace(viewId, mFragmentCustomerDetail);
        transaction.commit();
    }


    private void save() {

        Object[] infoSave = mFragmentCustomerDetail.onFinish();
        //格式是否正确
        if (!(Boolean) infoSave[0] && infoSave[1] != null) {
            Toast.makeText(getApplicationContext(), (String) infoSave[1], Toast.LENGTH_LONG).show();
            return;
        }

        mCustomerDetail = (CustomerDetail) (infoSave[2]);
        boolean avatarUpdate = !(Boolean) (infoSave[3]);
        if (CustomerConstant.CUSTOMER_DETAIL_MODE_ADD.equals(mCustomerMode)) {
            mModeToast = "创建";
            createCustomer(mCustomerDetail, avatarUpdate);
        } else {
            mModeToast = "更新";
            updateCustomer(mCustomerUuid, mCustomerDetail, avatarUpdate);
        }
    }

    private CustomerDetail mCustomerDetail;

    private void createCustomer(CustomerDetail customerDetail, boolean avatarNeedUpdate) {
        if (avatarNeedUpdate) {
            uploadToAli(customerDetail.getPortraitPath(), null, customerDetail);
        } else {
            ebtapi.createCustomer(customerDetail).compose(RxUtil.rxTransformer(this)).subscribe(getCustomerCUSubscriber(customerDetail));
        }
    }

    private void updateCustomer(String customerId, CustomerDetail customerDetail, boolean avatarNeedUpdate) {
        if (avatarNeedUpdate) {
            uploadToAli(customerDetail.getPortraitPath(), customerId, customerDetail);
        } else {
            ebtapi.updateCustomer(customerId, customerDetail).compose(RxUtil.rxTransformer(this)).subscribe(getCustomerCUSubscriber(customerDetail));
        }
    }

    private void uploadToAli(String portraitPath, String customerId, CustomerDetail customerDetail) {
        OSSUploader.uploadPortrait(portraitPath, new OnOSSUploadResponseListener(customerId, customerDetail));
    }

    class OnOSSUploadResponseListener implements OSSCompletedCallback<PutObjectRequest, PutObjectResult> {

        private String customerId;
        private CustomerDetail customerDetail;

        public OnOSSUploadResponseListener(String customerId, CustomerDetail customerDetail) {
            this.customerId = customerId;
            this.customerDetail = customerDetail;
        }

        @Override
        public void onSuccess(PutObjectRequest putObjectRequest, PutObjectResult putObjectResult) {
            if (putObjectRequest != null) {
                String url = OSSUploader.getPublicUrl(putObjectRequest.getBucketName(), putObjectRequest.getObjectKey());
                customerDetail.setPortraitPath(url);
                if (TextUtils.isEmpty(customerId)) {
                    ebtapi.createCustomer(customerDetail).compose(RxUtil.rxTransformer(ActivityCustomerDetail.this)).subscribe(getCustomerCUSubscriber(customerDetail));
                } else {
                    ebtapi.updateCustomer(customerId, customerDetail).compose(RxUtil.rxTransformer(ActivityCustomerDetail.this)).subscribe(getCustomerCUSubscriber(customerDetail));
                }
            }
        }

        @Override
        public void onFailure(PutObjectRequest putObjectRequest, ClientException e, ServiceException e1) {
            ToastUtil.showToast("头像上传失败");
            // 请求异常
            if (e != null) {
                // 本地异常如网络异常等
                e.printStackTrace();
            }
            if (e1 != null) {
                // 服务异常
                Log.e("ErrorCode", e1.getErrorCode());
                Log.e("RequestId", e1.getRequestId());
                Log.e("HostId", e1.getHostId());
                Log.e("RawMessage", e1.getRawMessage());
            }
        }
    }


    /**
     * 插入或替换CustomerSimple
     *
     * @param c
     */
    private void replaceCustomerSimple(CustomerDetail c) {
        if (c != null && c.getCustomerId() != null && c.getCustomerId().length() > 0) {
            CustomerData data = new CustomerData(this);
            boolean exists = data.isCustomerExisting(c.getCustomerId());
            if (exists) {
                data.updateCustomerToSimple(c);
            } else {
                data.insertCustomerToSimple(c);
            }
        }
    }

    private String mModeToast = "";

    private Observer<CustomerCRUDRetJson> getCustomerCUSubscriber(CustomerDetail customerDetail) {
        return new Observer<CustomerCRUDRetJson>() {

            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onComplete() {
            }

            @Override
            public void onError(Throwable e) {
                UIHelper.makeToast(ActivityCustomerDetail.this, getString(R.string.network_fail));
            }

            @Override
            public void onNext(CustomerCRUDRetJson customerCreateRetJson) {
                if (customerCreateRetJson == null) {
                    UIHelper.makeToast(ActivityCustomerDetail.this, getString(R.string.network_fail));
                    return;
                }
                if (customerCreateRetJson.error != null) {
                    UIHelper.makeToast(ActivityCustomerDetail.this, getString(R.string.network_fail));
                    return;
                }
                if (customerCreateRetJson.error == null) {
                    if (customerCreateRetJson.data == null) {
                        UIHelper.makeToast(ActivityCustomerDetail.this, getString(R.string.network_fail));
                        return;
                    } else {
                        if (mIsChooseMode) {
                            if (customerDetail != null) {
                                customerDetail.setCustomerId(customerCreateRetJson.data.customerId);
                            }
                            onChoose(customerDetail);
                        } else {
                            refreshMainList();
                        }
                        try {
                            replaceCustomerSimple(customerDetail);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        refreshCustomerItem(mCustomerDetail.getCustomerId());
                        onBackPressed();
                    }
                }
            }
        };
    }


    private void refreshMainList() {
        EventBus.getDefault().post(new EventCustomerListRefresh());
    }

    private void onChoose(CustomerDetail customerDetail) {
        if (customerDetail == null || TextUtils.isEmpty(customerDetail.getName())) {
            return;
        }
        CustomerModelNew customerModelNew = CustomerConvertUtil.convertCustomerDetailToCustomerModelNew(customerDetail);
        EventBus.getDefault().post(new EventCustomerChooseAdded(customerModelNew));
    }

    private void refreshCustomerItem(String customerId) {
        EventBus.getDefault().post(new EventCustomerRefresh(customerId));
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        overridePendingTransition(R.anim.slide_left_in, R.anim.slide_right_out);
    }
}
